package com.chujian.Activities;

import java.lang.reflect.Type;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chujian.Adapter.OrderCurrentDetailAdapter;
import com.chujian.Global.Global;
import com.chujian.Threads.HttpClientPostThread;
import com.chujian.Utils.Constan;
import com.chujian.Utils.JsonUtil;
import com.chujian.Utils.Util;
import com.chujian.model.FoodList;
import com.chujian.model.Order;
import com.chujian.orderingsystem.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


/**
 * 实现当前订单明细
 * @author 周映凯
 *
 */
public class OrderCurrentDetailConsumerActivity extends Activity implements OnClickListener,OnItemLongClickListener{
	private Button btn_left;
	private Button btn_right;
	private TextView tvTotalPrice;
	private boolean refreshFlag=false;
	private Button tvRefresh;
	private Order mOrder;
	private List<FoodList>mList;
	private String jsonOrder;
	private ListView mListView;
	private int food_back_position=-1;
	private int modifyPosition;
	private OrderCurrentDetailAdapter mAdapter;
	private Handler mHandler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			String str=(String) msg.obj;
			if(str.equals("checkOutSuccess")){
				Toast.makeText(getApplicationContext(), "结账成功", Toast.LENGTH_SHORT).show();
				Intent intent=new Intent(OrderCurrentDetailConsumerActivity.this, MainSellerActivity.class);
				startActivity(intent);
				OrderCurrentDetailConsumerActivity.this.finish();
			}else if(str.equals("checkOutFailed")){
				Toast.makeText(getApplicationContext(), "结账失败", Toast.LENGTH_SHORT).show();
			}else if(str.equals("foodBackSuccess")){
				Util.showTextLong(getApplicationContext(), "退菜成功");
				Float food_price=mOrder.getFoodList().get(food_back_position).getFoodPrice();
				float total_price=mOrder.getTotalPrice()-food_price;
				mOrder.setTotalPrice(total_price);
				tvTotalPrice.setText(total_price+"元");
				mOrder.getFoodList().remove(food_back_position);
				mAdapter.notifyDataSetChanged();
				food_back_position=-1;
				
				Intent intent=new Intent();
				Gson gson=new Gson();
				String orderJson=gson.toJson(mOrder);
				intent.putExtra("order_json", orderJson);
				intent.putExtra("modifyPosition", modifyPosition);
				setResult(1001, intent);
			}else if(str.equals("foodBackFailed")){
				Util.confirmDialog("警告：", "退菜失败", OrderCurrentDetailConsumerActivity.this);
				food_back_position=-1;
			}else if(str.equals("foodBackRequestSuccess")){
				Util.confirmDialog("提示：", "已经向店家发起退菜请求,请等待店家回复！", OrderCurrentDetailConsumerActivity.this);
				mOrder.getFoodList().get(food_back_position).setFoodStatus(1);
				mAdapter.notifyDataSetChanged();
			}else if(str.equals("foodBackRequestFailed")){
				Util.confirmDialog("警告！", "退菜请求失败，请重试", OrderCurrentDetailConsumerActivity.this);
			}else {
				mOrder=JsonUtil.OrderFromJson(str);
				mAdapter=new OrderCurrentDetailAdapter(OrderCurrentDetailConsumerActivity.this, tvTotalPrice, mOrder);
				mListView.setAdapter(mAdapter);
				tvTotalPrice.setText("合计："+mOrder.getTotalPrice()+"元");
				
				if(refreshFlag){
					Intent intent=new Intent();
					Gson gson=new Gson();
					String orderJson=gson.toJson(mOrder);
					intent.putExtra("order_json", orderJson);
					intent.putExtra("modifyPosition", modifyPosition);
					setResult(1001, intent);
					refreshFlag=false;
				}
				
				
			}
			
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.current_order_detail);
		initView();
		
		jsonOrder=getIntent().getStringExtra("orderJson");
		Log.i("info", jsonOrder);
		modifyPosition=getIntent().getIntExtra("position", -1);
		
		if(jsonOrder!=null&&!jsonOrder.equals("")){
			
		Log.i("info", jsonOrder);
//		Toast.makeText(OrderCurrentDetailConsumerActivity.this, jsonOrder, Toast.LENGTH_LONG).show();
		}else {
			jsonOrder=getIntent().getStringExtra("orderNotice");
		}
		mOrder=StringFromJson(jsonOrder);
//		mAdapter=new OrderCurrentDetailAdapter(OrderCurrentDetailConsumerActivity.this, tvTotalPrice, mOrder);
//		mListView.setAdapter(mAdapter);
//		tvTotalPrice.setText("合计："+mOrder.getTotalPrice()+"元");
		String url=Constan.BASE_URL+"OrderCurrentDetailOrderRefresh";
		new HttpClientPostThread(url, mHandler, mOrder.getOrderId()).start();

		
		
		
	}
	private void initView() {
//		初始化控件
		tvRefresh=(Button) findViewById(R.id.btn_c_o_d_refresh);
		mListView=(ListView) findViewById(R.id.lv_order_detail);
		btn_left=(Button) findViewById(R.id.btn_bottom_left);
		btn_right=(Button) findViewById(R.id.btn_bottom_right);
		tvTotalPrice=(TextView) findViewById(R.id.tv_bottom_total_price);
		btn_left.setOnClickListener(this);
		btn_right.setOnClickListener(this);
		mListView.setOnItemLongClickListener(this);
		tvRefresh.setOnClickListener(this);
		btn_left.setText("结账");
		btn_right.setText("加菜");
		btn_left.setBackgroundResource(R.drawable.brown_button_selector);

	}
	public Order StringFromJson(String jsondata){
			
			Type orderType=new TypeToken<Order>() {}.getType();
			Gson gson= new Gson();
			Order order=gson.fromJson(jsondata, orderType);
			return order;
			
		}

	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==2000&&resultCode==3002){
			String newAddOrder=data.getStringExtra("newAddOrder");
			Order order=JsonUtil.OrderFromJson(newAddOrder);
			mOrder.setTotalPrice(order.getTotalPrice()+mOrder.getTotalPrice());
			for(FoodList f:order.getFoodList()){
				mOrder.getFoodList().add(f);
			}
			mAdapter.notifyDataSetChanged();
			tvTotalPrice.setText(mOrder.getTotalPrice()+"元");
			
			data.putExtra("modifyPosition", modifyPosition);
			setResult(3003, data);
			
		}
	};
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_bottom_left:
//			结账
			Intent intent =new Intent(getApplicationContext(), PayBillConsumer.class);
			intent.putExtra("orderInfo", jsonOrder);
			startActivityForResult(intent, 1000);
			
			break;
		case R.id.btn_bottom_right:
//			加菜
			Intent intent2 =new Intent(getApplicationContext(), TakeOrderActivity.class);
//			intent2.putExtra("add_food_flag", true);
//			intent2.putExtra("tableName", mOrder.getTableName());
//			intent2.putExtra("orderID", mOrder.getTableName());
			Global.add_food_flag=true;
			Global.selectedTable=mOrder.getTableName();
			Global.orderAddId=mOrder.getOrderId();
			startActivityForResult(intent2, 2000);
			break;
		case R.id.btn_c_o_d_refresh:
			refreshFlag=true;
			Util.showTextShort(getApplicationContext(), "正在刷新订单信息");
			String url=Constan.BASE_URL+"OrderCurrentDetailOrderRefresh";
			new HttpClientPostThread(url, mHandler, mOrder.getOrderId()).start();
			break;
		default:
			;
		}
	}
	public void IbBack(View v){
		finish();
	}
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		if(mOrder.getFoodList().get(position).getFoodStatus()==1){
			
		}else if(mOrder.getFoodList().get(position).getFoodStatus()==2){
			
		}else {
			confirmDialog(position);
		}
		
		return true;
	}
	private void confirmDialog(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderCurrentDetailConsumerActivity.this);
//      builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle("弹出警告框");
        builder.setMessage("确定退菜吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
//            	if(food_back_position==-1){
	            		
		            int status=mOrder.getFoodList().get(position).getFoodStatus();
		            if(status==0){
		            	food_back_position=position;
		            	Util.showTextLong(getApplicationContext(), "正在发起退菜");
		            	Gson gson=new Gson();
		            	String jsonString=gson.toJson(mOrder.getFoodList().get(position));
		            	String url=Constan.BASE_URL+"FoodBackServlet";
		            	new HttpClientPostThread(url, mHandler, jsonString).start();
		            }else {
		            	Util.confirmDialog("警告：", "您的菜品已经制作，无法退菜！！", OrderCurrentDetailConsumerActivity.this);
		            }
		            	
//            	}else {
//            		Util.confirmDialog("警告：", "上一退菜操作尚未完成，请稍后再试！！", OrderCurrentDetailConsumerActivity.this);
//            	}
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
            }
        });
        builder.show();
	}
	
	public void refresh(View v){

		
	}
}
